package com.yu.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;  
import org.apache.commons.httpclient.HttpStatus;  
import org.apache.commons.httpclient.NameValuePair;  
import org.apache.commons.httpclient.methods.PostMethod;  

public class PostTest {
	
	public static String doPost(String url, Map<String, String> params, String charset) {  
        StringBuffer response = new StringBuffer();  
        HttpClient client = new HttpClient();  
        PostMethod method = new PostMethod(url);  
        // 设置Http Post数据  
        method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);  
        if(params != null){  
            Set<String> keySet = params.keySet();  
            NameValuePair[] param = new NameValuePair[keySet.size()];  
            int i = 0;  
            for(String key : keySet){  
                param[i] = new NameValuePair(key, params.get(key));  
                i++;  
            }  
            method.setRequestBody(param);  
        }  
        InputStream responseBodyStream = null;  
        InputStreamReader streamReader = null;  
        BufferedReader reader = null;  
        try {  
            client.executeMethod(method);  
            if (method.getStatusCode() == HttpStatus.SC_OK) {  
                responseBodyStream = method.getResponseBodyAsStream();  
                streamReader = new InputStreamReader(responseBodyStream, charset);  
                reader = new BufferedReader(streamReader);  
                String line;  
                while ((line = reader.readLine()) != null) {  
                    response.append(line);  
                }  
            }  
        } catch (Exception e) {  
        	e.printStackTrace();
        } finally {  
            try {  
                responseBodyStream.close();  
                streamReader.close();  
                reader.close();  
            } catch (IOException e) {  

                e.printStackTrace();  
            }  
            method.releaseConnection();  
        }  
        return response.toString();  
    }  
	
	
	public static void main(String[] args) {
		//PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	// 
            URL realUrl = new URL("http://file.carmap.me:9000/club/api/face/upload/61034864334556?multipartkey=image&format=png&imagetype=face");
            // 打开和URL之间的连接
            //URLConnection conn = realUrl.openConnection();
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(300000);
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("uid", "61034864334556");
            conn.setRequestProperty("udid", "web-admin");
            conn.setRequestProperty("sn", "sn1234");
            conn.setRequestProperty("sign", "sp_youche3");
            conn.setRequestProperty("token", "e446616d-19a9-426b-835c-4433e51fe1e9-it09vq16");
            conn.setRequestProperty("Content-MD5", "707dad8305e29ace6de55d9d575437c1");
            
            conn.setRequestProperty("capturetime", "1476262278");
            conn.setRequestProperty("restype", "101");
            conn.setRequestProperty("subtype", "0");
            conn.setRequestProperty("info", "30*30");

            conn.setRequestMethod("POST");
            final String newLine = "\r\n";
        	final String boundaryPrefix = "--";
        	// 定义数据分隔线
        	String BOUNDARY = "========7d4a6d158c9"; //D:\\img\\spring.png  multipartkey
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary="+BOUNDARY);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            // 获取URLConnection对象对应的输出流
            OutputStream out = conn.getOutputStream();
            // 发送请求参数
            //out.print(param);
            
        	String fileName =  "D:\\img\\spring.png";
        	File file = new File(fileName);
        	StringBuilder sb = new StringBuilder();
        	sb.append(boundaryPrefix);
        	sb.append(BOUNDARY);
        	sb.append(newLine);
        	// 文件参数,photo参数名可以随意修改
        	sb.append("Content-Disposition: form-data;name=\"image\";filename=\"" + fileName
        	        + "\"" + newLine);
        	sb.append("Content-Type:application/octet-stream");
        	// 参数头设置完以后需要两个换行，然后才是参数内容
        	sb.append(newLine);
        	// 将参数头的数据写入到输出流中
        	out.write(sb.toString().getBytes());
        	// 数据输入流,用于读取文件数据
        	DataInputStream inf = new DataInputStream(new FileInputStream(
        	        file));
        	byte[] bufferOut = new byte[1024];
        	int bytes = 0;
        	// 每次读1KB数据,并且将文件数据写入到输出流中
        	while ((bytes = inf.read(bufferOut)) != -1) {
        	    out.write(bufferOut, 0, bytes);
        	}
        	// 最后添加换行
        	out.write(newLine.getBytes());
        	inf.close();
        	// 定义最后数据分隔线，即--加上BOUNDARY再加上--。
        	byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
        	        .getBytes();
        	// 写上结尾标识
        	out.write(end_data);
       
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{

                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
	}
}
